<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>MQ消息测试</title>
    <style>
      body {
        font-family: Arial, sans-serif;
        max-width: 800px;
        margin: 0 auto;
        padding: 20px;
        background-color: #f5f5f5;
      }
      .container {
        background: white;
        padding: 30px;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      }
      h1 {
        color: #333;
        text-align: center;
        margin-bottom: 30px;
      }
      .form-group {
        margin-bottom: 20px;
      }
      label {
        display: block;
        margin-bottom: 5px;
        font-weight: bold;
        color: #555;
      }
      input,
      select,
      textarea {
        width: 100%;
        padding: 10px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;
      }
      textarea {
        height: 100px;
        resize: vertical;
      }
      button {
        background-color: #1890ff;
        color: white;
        padding: 12px 24px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 16px;
        margin-right: 10px;
      }
      button:hover {
        background-color: #40a9ff;
      }
      button:disabled {
        background-color: #ccc;
        cursor: not-allowed;
      }
      .result {
        margin-top: 20px;
        padding: 15px;
        border-radius: 4px;
        display: none;
      }
      .success {
        background-color: #f6ffed;
        border: 1px solid #b7eb8f;
        color: #52c41a;
      }
      .error {
        background-color: #fff2f0;
        border: 1px solid #ffccc7;
        color: #ff4d4f;
      }
      .loading {
        display: none;
        text-align: center;
        margin-top: 20px;
      }
      .loading::after {
        content: '';
        display: inline-block;
        width: 20px;
        height: 20px;
        border: 3px solid #f3f3f3;
        border-top: 3px solid #1890ff;
        border-radius: 50%;
        animation: spin 1s linear infinite;
      }
      @keyframes spin {
        0% {
          transform: rotate(0deg);
        }
        100% {
          transform: rotate(360deg);
        }
      }
    </style>
  </head>
  <body>
    <div class="container">
      <h1>MQ消息发送测试</h1>

      <div class="form-group">
        <label for="tenantId">租户ID:</label>
        <input type="text" id="tenantId" value="test001" placeholder="请输入租户ID" />
      </div>

      <div class="form-group">
        <label for="messageType">消息类型:</label>
        <select id="messageType">
          <option value="async">异步请求消息</option>
          <option value="sync">同步消息</option>
        </select>
      </div>

      <div class="form-group" id="timeoutGroup" style="display: none">
        <label for="timeout">超时时间(毫秒):</label>
        <input type="number" id="timeout" value="5000" min="1000" max="30000" />
      </div>

      <div class="form-group">
        <label for="message">消息内容:</label>
        <textarea id="message" placeholder="请输入消息内容">
{"message": "这是一条测试消息", "timestamp": "2025-01-06T12:00:00Z", "data": {"id": 123, "value": "test"}}</textarea
        >
      </div>

      <div class="form-group">
        <label for="properties">消息属性 (JSON格式):</label>
        <textarea id="properties" placeholder='{"key1": "value1", "key2": "value2"}'>
{"source": "test", "priority": "high"}</textarea
        >
      </div>

      <button onclick="sendMessage()">发送消息</button>
      <button onclick="clearResult()">清空结果</button>

      <div class="loading" id="loading">正在发送消息...</div>

      <div class="result" id="result"></div>
    </div>

    <script>
      // 监听消息类型变化
      document.getElementById('messageType').addEventListener('change', function () {
        const timeoutGroup = document.getElementById('timeoutGroup');
        if (this.value === 'sync') {
          timeoutGroup.style.display = 'block';
        } else {
          timeoutGroup.style.display = 'none';
        }
      });

      async function sendMessage() {
        // 功能：根据表单输入，调用同源后端接口发送 MQ 消息（异步/同步），并处理响应显示
        const tenantId = document.getElementById('tenantId').value.trim();
        const messageType = document.getElementById('messageType').value;
        const messageContent = document.getElementById('message').value.trim();
        const propertiesText = document.getElementById('properties').value.trim();
        const timeout = parseInt(document.getElementById('timeout').value);

        if (!tenantId) {
          showResult('请输入租户ID', 'error');
          return;
        }

        if (!messageContent) {
          showResult('请输入消息内容', 'error');
          return;
        }

        let properties = {};
        if (propertiesText) {
          try {
            properties = JSON.parse(propertiesText);
          } catch (e) {
            showResult('消息属性格式错误，请使用正确的JSON格式', 'error');
            return;
          }
        }

        const requestData = {
          message: messageContent,
          properties: Object.keys(properties).length > 0 ? properties : undefined
        };

        // 修改为同源路径，避免混合内容问题
        let url = `/api/mq/${messageType === 'async' ? 'async-req' : 'sync'}/${tenantId}/with-properties`;
        if (messageType === 'sync') {
          url += `?timeout=${timeout}`;
        }

        showLoading(true);

        try {
          const response = await fetch(url, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(requestData)
          });

          const result = await response.json();

          if (result.code === '0000') {
            showResult(`消息发送成功！\n响应: ${JSON.stringify(result, null, 2)}`, 'success');
          } else {
            showResult(`消息发送失败！\n错误: ${result.msg || '未知错误'}`, 'error');
          }
        } catch (error) {
          showResult(`网络错误: ${error.message}`, 'error');
        } finally {
          showLoading(false);
        }
      }

      function showResult(message, type) {
        // 功能：展示请求结果到页面（成功/失败）
        const resultDiv = document.getElementById('result');
        resultDiv.textContent = message;
        resultDiv.className = `result ${type}`;
        resultDiv.style.display = 'block';
      }

      function showLoading(show) {
        // 功能：切换加载中状态的显示与隐藏
        const loadingDiv = document.getElementById('loading');
        loadingDiv.style.display = show ? 'block' : 'none';
      }

      function clearResult() {
        // 功能：清空页面结果展示区
        document.getElementById('result').style.display = 'none';
      }
    </script>
  </body>
</html>
